﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OpenIddict.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.OpenIddict.Controllers;

namespace EcoSystem
{
    /// <summary>
    /// 重写获取token控制器
    /// </summary>
    [Dependency(ReplaceServices = true)]
    [ExposeServices(typeof(TokenController))]
    public class MyTokenController : TokenController
    {
        public IRepository<SystemUser, Guid> UserRepository { get; set; }

        /// <summary>
        /// 重写登录权限
        /// </summary>
        /// <returns></returns>
        public override async Task<IActionResult> HandleAsync()
        {
            OpenIddictRequest openIddictRequest = await GetOpenIddictServerRequestAsync(base.HttpContext).ConfigureAwait(continueOnCapturedContext: false);
            var account_type = (string)openIddictRequest.GetParameter("account_type")?.Value;
            var username = openIddictRequest.Username;
            if (string.IsNullOrEmpty(account_type))
            {
                return Forbid(new AuthenticationProperties(new Dictionary<string, string>
                {
                    [".error"] = "invalid_account_type",
                    [".error_description"] = "参数account_type不允许为空."
                }), "OpenIddict.Server.AspNetCore");
            }
            AccountType accountType = AccountType.AdminUser;
            if (account_type == "admin")
            {
                accountType = AccountType.AdminUser;
            }
            else if (account_type == "member")
            {
                accountType = AccountType.MemberUser;
            }
            else if (account_type == "enterpriser")
            {
                accountType = AccountType.EnterpriseUser;
            }
            if (!await UserRepository.AnyAsync(
                x => x.UserName == username && x.AccountType == accountType))
            {
                base.Logger.LogInformation("No user found matching username: {username}", username);
                //判断用户账号类型数据是否存在
                return Forbid(new AuthenticationProperties(new Dictionary<string, string>
                {
                    [".error"] = "invalid_grant",
                    [".error_description"] = "Invalid username or password!"
                }), "OpenIddict.Server.AspNetCore");
            }
            return await base.HandleAsync();
        }
    }
}
